<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    :close-on-click-modal="false"
    class="anti-forget-dialog"
    @close="handleClose"
  >
    <!-- 滚动容器 -->
    <div class="dialog-scroll-container">
      <!-- 主内容卡片 -->
      <div class="main-card">
        <!-- 开关控制区域 -->
        <div class="control-section">
          <div class="control-header">
            <div class="control-title">
              <i class="fas fa-cog control-icon"></i>
              <span>抗遗忘规则设置</span>
            </div>
            <div class="control-actions">
              <el-button
                icon="fas fa-undo"
                size="mini"
                class="reset-btn"
                :disabled="!isEnabled"
                @click="handleResetDefault"
              >
                重置默认
              </el-button>
              <el-switch
                v-model="isEnabled"
                active-color="#3498db"
                inactive-color="#dcdfe6"
                @change="handleSwitchChange"
              >
                <template #active>
                  <span class="switch-text">已开启</span>
                </template>
                <template #inactive>
                  <span class="switch-text">已关闭</span>
                </template>
              </el-switch>
            </div>
          </div>

          <!-- 提示信息 -->
          <div class="hint-box" :class="{ disabled: !isEnabled }">
            <i class="fas fa-info-circle hint-icon"></i>
            <div class="hint-content">
              <span class="hint-title">规则说明</span>
              <span class="hint-desc">基于本月1日上课计算抗遗忘日期（示例参考）</span>
              <span class="hint-desc"
              >修改抗遗忘生成规则后，不会影响已有的抗遗忘课程数据，下次课程结束后新设置才会生效！</span>
            </div>
          </div>
        </div>

        <!-- 规则设置区域 -->
        <div class="rules-section" :class="{ disabled: !isEnabled }">
          <div class="section-header">
            <i class="fas fa-calendar-alt section-icon"></i>
            <span class="section-title">抗遗忘规则列表</span>
            <span class="rules-count">{{ reviewDates.length }}条规则</span>
          </div>

          <!-- 规则表格 -->
          <div class="rules-table-container">
            <div class="table-header">
              <div class="header-cell">序号</div>
              <div class="header-cell">上课后第几天</div>
              <div class="header-cell">抗遗忘日期（示例）</div>
              <div class="header-cell action-cell">操作</div>
            </div>

            <div class="table-body">
              <div
                v-for="(item, index) in reviewDates"
                :key="index"
                class="table-row"
                :class="{ even: index % 2 === 0 }"
              >
                <div class="table-cell index-cell">
                  <span class="index-badge">{{ index + 1 }}</span>
                </div>
                <div class="table-cell">
                  <el-input-number
                    v-model="item.day"
                    :min="0"
                    :max="99"
                    :disabled="!isEnabled"
                    size="small"
                    controls-position="right"
                    class="day-input"
                    @change="handleDayChange(item, index)"
                  />
                </div>
                <div class="table-cell">
                  <el-date-picker
                    v-model="item.date"
                    type="date"
                    format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd"
                    :disabled="true"
                    placeholder="选择日期"
                    size="small"
                    class="date-picker"
                  />
                </div>
                <div class="table-cell action-cell">
                  <el-button
                    icon="fas fa-trash"
                    size="mini"
                    class="delete-btn"
                    :disabled="!isEnabled || reviewDates.length <= 1"
                    :title="reviewDates.length <= 1 ? '至少保留一条规则' : '删除规则'"
                    @click="handleDelete(index)"
                  />
                </div>
              </div>
            </div>
          </div>

          <!-- 新增按钮 -->
          <el-button
            icon="fas fa-plus"
            size="small"
            class="add-btn"
            :disabled="!isEnabled"
            @click="handleAdd"
          >
            新增抗遗忘规则
          </el-button>
        </div>
      </div>
    </div>

    <!-- 底部按钮 -->
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose" class="cancel-btn">取消</el-button>
      <el-button
        type="primary"
        :loading="loading"
        @click="handleSave"
        class="save-btn"
      >
        <i class="fas fa-save"></i>
        保存设置
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getAntiForgetSetting, updateAntiForgetSetting } from '@/api/antiForget'

export default {
  name: 'AntiForgetRuleDialog',
  props: {
    title: {
      type: String,
      default: '自定义抗遗忘规则'
    },
    visible: {
      type: Boolean,
      default: false
    },
    student: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      loading: false,
      isEnabled: true,
      defaultReviewDates: [
        { day: 1, date: '' }, { day: 2, date: '' }, { day: 3, date: '' },
        { day: 5, date: '' }, { day: 7, date: '' }, { day: 9, date: '' },
        { day: 12, date: '' }, { day: 14, date: '' }, { day: 17, date: '' },
        { day: 21, date: '' }
      ],
      reviewDates: []
    }
  },
  computed: {
    baseClassDate() {
      const date = new Date()
      date.setDate(1)
      return date
    }
  },
  created() {
    if (this.student) {
      this.title = `设置${this.student.name}的抗遗忘规则`
    }
    this.loadData()
  },
  methods: {
    async loadData() {
      this.loading = true
      try {
        const res = await getAntiForgetSetting({ studentId: this.student.id })
        this.isEnabled = res.antiForgetOpen
        res.antiForgetDate.forEach(item => {
          this.reviewDates.push({ day: item * 1, date: '' })
        })
        this.calculateAllDates()
      } catch (error) {
        console.error(error)
      } finally {
        this.loading = false
      }
    },

    calculateAllDates() {
      this.reviewDates.forEach(item => {
        this.calculateSingleDate(item)
      })
    },

    calculateSingleDate(item) {
      const targetDate = new Date(this.baseClassDate)
      targetDate.setDate(this.baseClassDate.getDate() + item.day)
      item.date = this.formatDate(targetDate)
    },

    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },

    handleDayChange(row, index) {
      const hasDuplicate = this.reviewDates.some((item, i) => {
        return i !== index && item.day === row.day
      })
      if (hasDuplicate) {
        // 自动调整天数
        const arr = new Array(100).fill(0)
        this.reviewDates.forEach(item => {
          arr[item.day] = 1
        })
        for (let i = 1; i < arr.length; i++) {
          if (arr[i] === 0 && i !== row.day - 1) {
            row.day = i
            break
          }
        }
        this.$notify({ type: 'warning', message: '天数不能重复，已自动调整' })
      }
      this.calculateSingleDate(row)
    },

    handleAdd() {
      const lastDay = this.reviewDates[this.reviewDates.length - 1].day
      const newItem = { day: lastDay + 1, date: '' }
      this.calculateSingleDate(newItem)
      this.reviewDates.push(newItem)
    },

    handleDelete(index) {
      this.reviewDates.splice(index, 1)
    },

    handleResetDefault() {
      this.$confirm('确定要重置为默认抗遗忘规则吗？当前设置将被覆盖', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.reviewDates = JSON.parse(JSON.stringify(this.defaultReviewDates))
        this.calculateAllDates()
        this.$notify({ type: 'success', message: '已重置为默认规则' })
      })
    },

    handleSwitchChange(checked) {
      this.isEnabled = checked
    },

    async handleSave() {
      this.loading = true
      try {
        const sortedDates = [...this.reviewDates].sort((a, b) => a.day - b.day)
        const dateArr = []
        sortedDates.forEach(item => {
          dateArr.push(item.day)
        })
        await updateAntiForgetSetting({
          studentId: this.student.id,
          antiForgetOpen: this.isEnabled,
          antiForgetDate: dateArr
        })
        this.$notify({ type: 'success', message: '设置保存成功' })
        this.handleClose()
      } catch (error) {
        this.$notify({ message: '数据保存失败，请重试', type: 'error' })
        console.error(error)
      } finally {
        this.loading = false
      }
    },

    handleClose() {
      this.$emit('update:visible', false)
    }
  }
}
</script>

<style scoped>
/* 对话框整体样式 */
.anti-forget-dialog ::v-deep .el-dialog {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.2);
}

.anti-forget-dialog ::v-deep .el-dialog__header {
  background: linear-gradient(135deg, #3498db 0%, #2c3e50 100%);
  padding: 20px;
  margin: 0;
}

.anti-forget-dialog ::v-deep .el-dialog__title {
  color: white;
  font-size: 18px;
  font-weight: 600;
}

.anti-forget-dialog ::v-deep .el-dialog__headerbtn {
  top: 20px;
}

.anti-forget-dialog ::v-deep .el-dialog__headerbtn .el-dialog__close {
  color: white;
}

.anti-forget-dialog ::v-deep .el-dialog__body {
  padding: 0;
  background: #f8fafc;
}

/* 滚动容器 */
.dialog-scroll-container {
  height: 60vh;
  overflow-y: auto;
  padding: 20px;
}

.dialog-scroll-container::-webkit-scrollbar {
  width: 6px;
}

.dialog-scroll-container::-webkit-scrollbar-thumb {
  background: linear-gradient(135deg, #3498db, #2c3e50);
  border-radius: 3px;
}

/* 主卡片 */
.main-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

/* 控制区域 */
.control-section {
  padding: 24px;
  border-bottom: 1px solid #f0f2f5;
}

.control-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.control-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}

.control-icon {
  margin-right: 12px;
  color: #3498db;
  font-size: 20px;
}

.control-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.reset-btn {
  background: linear-gradient(135deg, #e74c3c, #c0392b);
  color: white;
  border: none;
  border-radius: 8px;
  padding: 8px 16px;
}

.reset-btn:disabled {
  background: #bdc3c7;
  cursor: not-allowed;
}

/* 提示框 */
.hint-box {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  background: linear-gradient(135deg, #e8f4ff, #d6eaf8);
  border-radius: 8px;
  border-left: 4px solid #3498db;
}

.hint-box.disabled {
  background: #f8f9fa;
  border-left-color: #bdc3c7;
}

.hint-icon {
  color: #3498db;
  font-size: 18px;
  margin-right: 12px;
}

.hint-content {
  display: flex;
  flex-direction: column;
}

.hint-title {
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 2px;
}

.hint-desc {
  color: #7f8c8d;
  font-size: 14px;
}

/* 规则区域 */
.rules-section {
  padding: 24px;
}

.rules-section.disabled {
  opacity: 0.6;
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.section-icon {
  color: #3498db;
  margin-right: 8px;
  font-size: 16px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  margin-right: 12px;
}

.rules-count {
  background: #3498db;
  color: white;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
}

/* 自定义表格 */
.rules-table-container {
  border: 1px solid #e1e8ed;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 20px;
}

.table-header {
  display: grid;
  grid-template-columns: 80px 1fr 1fr 100px;
  background: linear-gradient(135deg, #f8f9fa, #e9ecef);
  border-bottom: 1px solid #e1e8ed;
}

.header-cell {
  padding: 16px 12px;
  font-weight: 600;
  color: #2c3e50;
  text-align: center;
}

.action-cell {
  text-align: center;
}

/*.table-body {
  max-height: 300px;
  overflow-y: auto;
}*/

.table-row {
  display: grid;
  grid-template-columns: 80px 1fr 1fr 100px;
  border-bottom: 1px solid #f0f2f5;
  transition: all 0.3s ease;
}

.table-row:hover {
  background-color: #f8fafc;
}

.table-row.even {
  background-color: #fafbfc;
}

.table-row.even:hover {
  background-color: #f1f3f4;
}

.table-cell {
  padding: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.index-cell {
  justify-content: center;
}

.index-badge {
  background: linear-gradient(135deg, #3498db, #2980b9);
  color: white;
  width: 28px;
  height: 28px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: 600;
}

/* 输入组件样式 */
.day-input ::v-deep .el-input-number {
  width: 100px;
}

.date-picker ::v-deep .el-date-editor {
  width: 140px;
}

/* 删除按钮 */
.delete-btn {
  color: #FFFFFF;
  background-color: #e74c3c;
  border: none;
  padding: 6px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.delete-btn:hover:not(:disabled) {
  background-color: #ffeaea;
  color: #c0392b;
}

.delete-btn:disabled {
  color: #bdc3c7;
  cursor: not-allowed;
}

/* 新增按钮 */
.add-btn {
  background: linear-gradient(135deg, #27ae60, #229954);
  color: white;
  border: none;
  border-radius: 8px;
  padding: 10px 20px;
  width: 100%;
  transition: all 0.3s ease;
}

.add-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(39, 174, 96, 0.3);
}

.add-btn:disabled {
  background: #bdc3c7;
  cursor: not-allowed;
}

/* 底部按钮 */
.dialog-footer {
  padding: 20px;
  background: #f8fafc;
  border-top: 1px solid #e1e8ed;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.cancel-btn {
  border: 1px solid #bdc3c7;
  color: #7f8c8d;
  border-radius: 8px;
  padding: 10px 24px;
}

.save-btn {
  background: linear-gradient(135deg, #3498db, #2980b9);
  border: none;
  border-radius: 8px;
  padding: 10px 24px;
  transition: all 0.3s ease;
}

.save-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(52, 152, 219, 0.3);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .anti-forget-dialog ::v-deep .el-dialog {
    width: 95% !important;
    margin: 20px auto;
  }

  .control-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }

  .table-header,
  .table-row {
    grid-template-columns: 60px 1fr 1fr 80px;
  }
}
</style>
